package httpx

import (
	"fmt"
	"net"
	"strconv"
	"strings"

	"xp/lib/log"
	"xp/lib/md"

	http "github.com/valyala/fasthttp"
)

type Server struct {
	*http.Server

	ln   net.Listener
	port int
}

func NewServer(srv *http.Server, ln net.Listener) (*Server, error) {
	s := &Server{Server: srv, ln: ln}
	addrs := strings.Split(ln.Addr().String(), ":")
	if len(addrs) == 2 {
		port, err := strconv.Atoi(addrs[1])
		if err != nil {
			log.Fatal("err", err.Error())
		}
		s.port = port
	}
	md.ListeningOn(s.port)
	go s.Serve(ln)
	return s, nil
}

func (s *Server) Addr() string {
	return s.ln.Addr().String()
}

func (s *Server) Port() int {
	return s.port
}

func (s *Server) Close() error {
	return s.ln.Close()
}

func ListenAndServe(port int, handler http.RequestHandler) (*Server, error) {
	addr := fmt.Sprintf(":%d", port)
	srv := &http.Server{
		Handler:            handler,
		Name:               md.GetService(),
		MaxRequestBodySize: 1 << 20, // default 1M
	}
	if addr == "" {
		addr = ":http"
	}
	ln, err := net.Listen("tcp4", addr)
	if err != nil {
		return nil, err
	}
	return NewServer(srv, ln)
}
